﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using C3.Directory.Services;
using CSI.Directory.Core.Model;
using CSI.Directory.Core.Services;
using CSI.Directory.Web.Filters;
using HtmlAgilityPack;
using StructureMap;

namespace CSI.Directory.Web.Controllers
{
    [HandleError]
    public class DirectoryController : BaseController
    {
        public DirectoryController()
        {
            pageSize = Convert.ToInt32(ConfigurationManager.AppSettings["pageSize"]);
        }

       
        private int pageSize;

        public ActionResult Oops(string message)
        {
            ViewData["Error"] = message;
            return View();
        }

        public ActionResult Index()
        {
            
            ViewData["Categories"] = DirectoryService.GetAllCategories();

            ViewData["Counties"] = DirectoryService.GetAllCounties().OrderBy(t=>t.Name).ToList();
            ViewData["Featured"] = DirectoryService.GetFeaturedListings().OrderBy(t => t.Name).ToList();
            return View();
        }

        //public ActionResult GetCategory(string category)
        //{
        //    var cat = DirectoryService.GetCategoryByName(category);
        //    if (cat == null) return RedirectToAction("Oops");
        //    ViewData["Listings"] = DirectoryService.GetListingsByCategory(cat.Id);
        //    ViewData["SubCategories"] = DirectoryService.GetSubCategoriesForCategory(cat.Id);
        //    ViewData["Category"] = cat;
        //    return View();
        //}
        public ActionResult GetCategory(int id,int? page)
        {
            var cat = DirectoryService.GetParentCategoryById(id);
            if (cat == null) return RedirectToAction("Oops");
            ViewData["SubCategories"] = DirectoryService.GetSubCategoriesForCategory(cat.Id);
            ViewData["Category"] = cat;
            var listings = DirectoryService.GetListingsByCategory(cat.Id);
            var total = listings.Count / pageSize;
            if((listings.Count % pageSize) > 0){total += 1;}
            ViewData["Pages"] = total;
            
            if (listings.Count < pageSize)
            {
                ViewData["Listings"] = listings;
                return View();
            }
            var p = (page) ?? 0;
            ViewData["Page"] = p;
            if (p <= 1)
            {
                ViewData["Listings"] = listings.Take(pageSize).ToList();
                ViewData["Page"] = 1;
                return View();
            }

            //10 listings, page = 2, (page - 1) * 7 = (2 - 1) * 7 = 7 | (3 - 1) * 7 = 14 | (4 - 1) * 7 = 21

            if (listings.Count > ((p - 1) * pageSize))
            {
                var l = listings.Skip((pageSize * (p - 1)));
                l = l.Take(pageSize).ToList();
                ViewData["Listings"] = l;
                return View();
            }

            ViewData["Listings"] = listings.Take(pageSize).ToList();
            ViewData["Page"] = 1;
            return View();

        }
        public ActionResult GetSubCategory(string category, string subcategory, int? page)
        {
            var cat = DirectoryService.GetParentCategoryByName(category);
            if (cat == null) return RedirectToAction("Oops");
            var subcats = DirectoryService.GetSubCategoriesForCategory(cat.Id);
            var subcat = subcats.SingleOrDefault(t => t.Name == subcategory);
            if (subcat == null) return RedirectToAction("Oops");
            ViewData["SubCategory"] = subcat;
            ViewData["Category"] = cat;

            var listings = DirectoryService.GetListingsByCategory(subcat.Id);
            var total = listings.Count / pageSize;
            if ((listings.Count % pageSize) > 0) { total += 1; }
            ViewData["Pages"] = total;
            
            if (listings.Count < pageSize)
            {
                ViewData["Listings"] = listings;
                return View();
            }
            var p = (page) ?? 0;
            ViewData["Page"] = p;
            if (p <= 1)
            {
                ViewData["Listings"] = listings.Take(pageSize).ToList();
                ViewData["Page"] = 1;
                return View();
            }

            //10 listings, page = 2, (page - 1) * 7 = (2 - 1) * 7 = 7 | (3 - 1) * 7 = 14 | (4 - 1) * 7 = 21

            if (listings.Count > ((p - 1) * pageSize))
            {
                var l = listings.Skip((pageSize * (p - 1)));
                l = l.Take(pageSize).ToList();
                ViewData["Listings"] = l;
                return View();
            }

            ViewData["Listings"] = listings.Take(pageSize).ToList();
            ViewData["Page"] = 1;
            return View();

            
        }
        public JsonResult GetSubCategoriesForCategory(int id)
        {
            return Json(DirectoryService.GetSubCategoriesForCategory(id));
        }

        [RestrictedAction(new[] { "user" }, null)]
        public ActionResult NewListing()
        {
           
            return View();
        }

        [RestrictedAction(new[] { "user" }, null)]
        public ActionResult FreeListing()
        {
           
            return View();
        }


        public ActionResult Search(string query, int category, int county, int? page)
        {
            
            ViewData["Listings"] = DirectoryService.SearchDirectory(query.Trim(), category, county).OrderBy(t=>t.Featured).ToList();
            
            return View();
        }


        [AcceptVerbs(HttpVerbs.Post)]
        [RestrictedAction(new[] { "user" }, null)]
        public ActionResult AddNewListing(int userid, string contact, string title, string email, string url, string phone, string address, string address2,
            string city, string state, string zipcode, string description, string keywords, 
            string category1, string category2, string category3, string category4, string category5,
            string category6, string category7, string category8, string category9, string category10, 
            string county1, string county2, string county3, string county4, string county5)
        {
            
            var t = DirectoryService.AddListing(userid, contact,  title,  email,  url,  phone,  address,  address2, city,  state,  
                zipcode,  description,  keywords,  category1,  category2,  category3, category4, category5,
                category6, category7, category8, category9, category10, 
                county1,  county2,  county3,  county4,  county5);
            return (t.Successful)
                       ? RedirectToAction("Thanks", new { name = title })
                       : RedirectToAction("Oops", "Directory", new { message = t.Exception });
            
        }

         [AcceptVerbs(HttpVerbs.Post)]
        [RestrictedAction(new[] { "user" }, null)]
        public ActionResult EditListing(int id, string contact, string title, string email, string url, string phone, string address, string address2,
                                          string city, string state, string zipcode, string description, string keywords)
        {

             var t = DirectoryService.EditListing(id, contact, title, email, url, phone,
                                                  address, address2, city, state, zipcode, description, keywords);
            return (t.Successful)
                       ? RedirectToAction("Listing", new { id = id })
                       : RedirectToAction("Oops", "Directory", new { message = t.Exception });

        }

        public ActionResult Listing(int id, string name)
        {
            ViewData["Listing"] = DirectoryService.GetListingById(id);
            return View();
        }
        [RestrictedAction(new[] { "user" }, null)]
        public ActionResult ManageListing(int id)
        {
            var l = DirectoryService.GetListingByUserId(id);
            if (SessionService.CurrentUser.Id != l.UserId)
                return RedirectToAction("Index");
            ViewData["Listing"] = l;
            return View();
        }
        [AcceptVerbs(HttpVerbs.Post)]
        [RestrictedAction(new[] { "user" }, null)]
        public ActionResult AddFreeListing(int userid, string title, string contact, string phone,
            string category1, string county1)
        {

            var t = DirectoryService.AddFreeListing(userid, title, contact, phone, category1, county1);
            return (t.Successful)
                       ? RedirectToAction("Thanks", new { name = title })
                       : RedirectToAction("Oops", "Directory", new { message = t.Exception });

        }
        public ActionResult Thanks(string name)
        {
            ViewData["Title"] = name;
            return View();

        }


        public ActionResult County(string name, int? page)
        {
            var c =  DirectoryService.GetCountyByName(name);
            if (c == null) return RedirectToAction("Oops", "Directory", new { message = "County not found." });
            var listings = DirectoryService.GetListingsByCounty(c.Id);
            ViewData["County"] = c;
            var total = listings.Count / pageSize;
            if ((listings.Count % pageSize) > 0) { total += 1; }
            ViewData["Pages"] = total;

            if (listings.Count < pageSize)
            {
                ViewData["Listings"] = listings;
                return View("GetCounty");
            }
            var p = (page) ?? 0;
            ViewData["Page"] = p;
            if (p <= 1)
            {
                ViewData["Listings"] = listings.Take(pageSize).ToList();
                ViewData["Page"] = 1;
                return View("GetCounty");
            }

            //10 listings, page = 2, (page - 1) * 7 = (2 - 1) * 7 = 7 | (3 - 1) * 7 = 14 | (4 - 1) * 7 = 21

            if (listings.Count > ((p - 1) * pageSize))
            {
                var l = listings.Skip((pageSize * (p - 1)));
                l = l.Take(pageSize).ToList();
                ViewData["Listings"] = l;
                return View("GetCounty");
            }

            ViewData["Listings"] = listings.Take(pageSize).ToList();
            ViewData["Page"] = 1;
            return View("GetCounty");
        }

    }
}